import axios from 'axios'; // 引入axios
import QS from 'qs'; // 引入qs模块，用来序列化post类型的数据，后面会提到
import store from './../store/store'
import * as types from './../store/types'
import router from 'vue-router'

// axios 配置
axios.defaults.timeout = 6 * 1000;
axios.defaults.baseURL = 'https://api.github.com';

// http request 拦截器
axios.interceptors.request.use(
  config => {
    if (store.state.token) {
      config.headers.Authorization = `token ${store.state.token}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  },
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 401 清除token信息并跳转到登录页面
          store.commit(types.LOGOUT)
          
          // 只有在当前路由不是登录页面才跳转
          router.currentRoute.path !== 'login' &&
            router.replace({
              path: 'login',
              query: { redirect: router.currentRoute.path },
            })
      }
    }
    // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
    return Promise.reject(error.response.data)
  },
)

/**
* get方法，对应get请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function get(url, params){    
   return new Promise((resolve, reject) =>{        
       axios({
           method: 'get',
           url: url,
           data: params
       }).then(res => {
               resolve(res.data);
           }).catch(err =>{
               reject(err.data)        
       })    
   });
}


/** 
* post方法，对应post请求 
* @param {String} url [请求的url地址] 
* @param {Object} params [请求时携带的参数] 
*/
export function post(url, params) {
   return new Promise((resolve, reject) => {
       axios({
           method: 'post',
           url: url,
           data: QS.stringify(params)
       })
       .then(res => {
           resolve(res.data);
       })
       .catch(err =>{
           reject(err.data)
       })
   });
}